#!/bin/sh

# test for root
if [ $(id -u) -ne 0 ]
    then
    echo "Sorry, you need to be root to run make_nodes script!"
    exit
fi

# if /etc/udev/udev.conf exists then udev support is installed
# find udev_rules directory entry in file and
# copy 10-iowarrior.rules into that directory
# default is /etc/udev/rules.d
# this is independent from udevd running
UDEVCFG="/etc/udev/udev.conf"

if [ -f $UDEVCFG ]
  then
  echo "Configuring udev support..."
  RULES_DIR=$(awk '/^ *udev_rules *= *\"/ {split($$1,parts,"\""); print parts[2]}' $UDEVCFG)
  if [ $RULES_DIR = "" ]
    then
    RULES_DIR="/etc/udev/rules.d"
  fi
  if [ -d $RULES_DIR ]
    then
    cp 10-iowarrior.rules $RULES_DIR
    echo "Copied rules file 10-iowarrior.rules into $RULES_DIR"
  fi
fi

# now test if udevd is running aka udev active
# if not then create static device nodes
DEVICE="iowarrior"
MAJOR=180
MINORBASE=208
MAXDEVICE=16

ps -C udevd >/dev/null
ISUDEV=$?
if [ $ISUDEV -ne 0 ]
  then
  # create static device nodes
  # first remove all existing devices
  rm -f /dev/usb/iowarrior*
  # create /dev/usb/iowarrior0 to /dev/usb/iowarrior15
  echo "Creating device nodes for the IO-Warrior..."
  OFFSET=0
  MINOR=$MINORBASE

  while [ $OFFSET -lt $MAXDEVICE ]
  do
    mknod -m 666 /dev/usb/${DEVICE}${OFFSET} c $MAJOR $MINOR
    echo "Created /dev/usb/${DEVICE}${OFFSET}"
    OFFSET=`expr $OFFSET + 1`
    MINOR=`expr $MINORBASE + $OFFSET`
  done
fi

echo "Device installation completed!"